//
//  HotViewController.swift
//  GroupApp
//
//  Created by 语安 on 16/8/15.
//  Copyright © 2016年 thls.com. All rights reserved.
//

import UIKit

class HotViewController: RootViewController, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate {
    
    var myScrollView = UIScrollView()
    var dataArray = [HeaderTitleModel]()
    var buttonArray = [UIButton]()
    var currentIndex = 0
    
    var areaCode = 0
    var listType = "all"
    
    var myTableView = UITableView()
    
    var cityArray = [CityModel]()
    var scenicArray = [ScenicModel]()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        createNav()
        
        loadData()
        
        loadDetailData()
    }
    
    //加载详细数据
    func loadDetailData() {
        
        let manager = AFHTTPSessionManager()
        
        manager.GET("http://apiphp.yaochufa.com/portal/dest/scenicCity?areaCode=\(self.areaCode)&system=ios&channel=AppStore&listType=\(self.listType)&imei=D4AC422E-C516-4EFB-B665-38CB6471887E&lang=app&version=5.2.4", parameters: nil, success: { (dataTask: NSURLSessionDataTask?, resp: AnyObject?) -> Void in
            
            let content = resp?.objectForKey("content")
            
            let hotCityArray = content?.objectForKey("hotCity") as! [[String:AnyObject]]
            for dic in hotCityArray {
                let model = CityModel()
                model.setValuesForKeysWithDictionary(dic)
                self.cityArray.append(model)
            }
            
            let hotScenicArray = content?.objectForKey("hotScenic") as! [[String:AnyObject]]
            for dic in hotScenicArray {
                let model = ScenicModel()
                model.setValuesForKeysWithDictionary(dic)
                self.scenicArray.append(model)
            }
            
            
            
            //刷新UI
            self.myTableView.reloadData()
            
            }) { (dataTask: NSURLSessionDataTask?, error: ErrorType?) -> Void in
                
                print(error)
        }
        
    }
    

    //加载数据
    func loadData() {
        
        let manager = AFHTTPSessionManager()
        
        manager.GET("http://apiphp.yaochufa.com/portal/dest/provinceList?version=5.1.2&system=ios&channel=AppStore&imei=5C313A72-0D36-498D-A9C3-B857F15E4293", parameters: nil, success: { (dataTask: NSURLSessionDataTask?, resp: AnyObject?) -> Void in
            
            let array = resp?.objectForKey("content") as! [[String:AnyObject]]
            for dic in array {
                let model = HeaderTitleModel()
                model.setValuesForKeysWithDictionary(dic)
                self.dataArray.append(model)
            }
            
            //刷新UI
            self.createUI()
            
            }) { (dataTask: NSURLSessionDataTask?, error: ErrorType?) -> Void in
                
                print(error)
        }
        
    }
    
    
    
    //创建UI
    func createUI() {
        
        myScrollView = UIScrollView(frame: CGRectMake(0, 0, screenWidth, 40))
        myScrollView.backgroundColor = UIColor.lightGrayColor()
        myScrollView.contentSize = CGSizeMake(screenWidth / 6 * CGFloat(dataArray.count), 40)
        myScrollView.bounces = false
        myScrollView.showsHorizontalScrollIndicator = false
        myScrollView.showsVerticalScrollIndicator = false
        myScrollView.delegate = self
        
        //添加按钮
        for i in 0 ..< dataArray.count {
            let model = dataArray[i]
            let button = UIButton(type: UIButtonType.Custom)
            button.frame = CGRectMake(CGFloat(i) * screenWidth / 5, 0, screenWidth / 5, 40)
            button.tag = 100 + i
            button.setTitle(model.name!, forState: UIControlState.Normal)
            button.setTitleColor(UIColor.RGBA(255, 156, 187), forState: UIControlState.Selected)
            buttonArray.append(button)
            button.addTarget(self, action: "typeButtonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
            myScrollView.addSubview(button)
        }
        
        self.view.addSubview(myScrollView)
        
        myTableView = UITableView(frame: CGRectMake(0, 40, screenWidth, screenHeight - 60), style: UITableViewStyle.Grouped)
        myTableView.delegate = self
        myTableView.dataSource = self
        myTableView.tableFooterView = UIView()
        
        self.view.addSubview(myTableView)
        
        //注册cell
        myTableView.registerClass(HotCityListCell.self, forCellReuseIdentifier: "hotListCell")
        myTableView.registerClass(HotScenicCell.self, forCellReuseIdentifier: "hotScenicCell")
    }
    
    
    func typeButtonClicked(button: UIButton) {
        
        cityArray.removeAll()
        scenicArray.removeAll()
        
        for btn in buttonArray {
            btn.selected = false
        }
        button.selected = true
      
        if button.tag > 102 {
            myScrollView.contentOffset.x = CGFloat(button.tag - 102) * screenWidth / 5
        }
        else {
            myScrollView.contentOffset.x = 0
        }
        currentIndex = button.tag - 100
        let model = dataArray[button.tag - 100]
        if button.tag == 101 {
            areaCode = 0
            listType = "all"
        }
        else {
            areaCode = model.areaCode
            listType = model.listType!
        }
        loadDetailData()
    }
    
    func createNav() {
        self.titleLabel?.text = "热门"
        self.titleLabel?.textColor = UIColor.whiteColor()
    }
    
    //MARK: 实现代理
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier("hotScenicCell", forIndexPath: indexPath) as! HotScenicCell
            
            cell.modelArray = scenicArray
            cell.colView?.frame = CGRect(x: 0, y: 0, width: cell.contentView.bounds.size.width, height: cell.contentView.bounds.size.height)
            cell.colView?.reloadData()
            
            return cell
        }
        else {
            let cell = tableView.dequeueReusableCellWithIdentifier("hotListCell", forIndexPath: indexPath) as! HotCityListCell
            
            if cityArray.count > 0 {
                cell.modelArray = cityArray
                cell.colView?.frame = CGRectMake(0, 0, cell.contentView.bounds.size.width, cell.contentView.bounds.size.height)
                cell.colView?.reloadData()
            }
            return cell
        }
        
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 110 * CGFloat(scenicArray.count / 2)
        }
        else {
            return 110 * CGFloat(cityArray.count / 2)
        }
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let titleLabel = Factory.createLabelWith(CGRectMake(screenWidth / 2, 0, 100, 40), text: "", font: UIFont.systemFontOfSize(18), textAlignment: NSTextAlignment.Center, textColor: UIColor.redColor())
        
        let model = dataArray[currentIndex]
        
        if section == 0 {
            if currentIndex == 0 {
                titleLabel.text = "全国热门景区"
            }
            else {
                titleLabel.text = "\(model.name!)热门景区"
            }
        }
        else {
            if currentIndex == 0 {
                titleLabel.text = "全国热门城市"
            }
            else {
                if model.name == "上海" || model.name == "澳门" || model.name == "香港" || model.name == "北京" || model.name == "重庆" {
                    titleLabel.text = "\(model.name!)周边城市"
                }
                else {
                    titleLabel.text = "\(model.name!)热门城市"
                }
            }
            
        }
        
        return titleLabel
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 40
    }

}
